package com.matt.service.care.impl;


import com.matt.domain.care.HLHandoverRecord;
import com.matt.domain.care.HLHandoverRecordMedicine;
import com.matt.repository.care.HLHandoverRecordMedicineRepository;
import com.matt.repository.care.HLHandoverRecordRepository;
import com.matt.service.care.HLHandoverRecordService;
import com.matt.service.care.po.HLHandoverRecordMedicinePO;
import com.matt.service.care.po.HLHandoverRecordPO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class HLHandoverRecordServiceImpl extends HLCareBaseServiceImpl<HLHandoverRecord, HLHandoverRecordRepository, HLHandoverRecordPO> implements HLHandoverRecordService {

	@Autowired
	@Override
	public void setBaseRepository(HLHandoverRecordRepository repository){
		super.setBaseRepository(repository);
	}

	@Autowired
	private HLHandoverRecordMedicineRepository medicineRepository;

	@Override
	public void delete(String areaId, String parentId, String childId, String id) {
		HLHandoverRecord t = get(areaId, parentId, childId, id);

		if (t == null || t.getSourceFrom() != 1){
			throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "记录不存在");
		}

		t.setDeleted(true);

		baseRepository.save(t);
	}

	@Override
	@Transactional(rollbackOn = RuntimeException.class)
	public HLHandoverRecord add(String parentId, BindedBabyVO bindedBabyVO, HLHandoverRecordPO param) {
		List<HLHandoverRecordMedicinePO> medicines = param.getMedicines();
		param.setMedicines(null);

		HLHandoverRecord ret = super.add(bindedBabyVO.getAreaId(), bindedBabyVO.getId(), param);

		if (medicines == null){
			return ret;
		} else {
			if (StringUtils.isNotBlank(param.getId())){
				medicineRepository.deleteAllByHandoverRecord(ret);
			}
			List<HLHandoverRecordMedicine> batch = new ArrayList<>();
			for (HLHandoverRecordMedicinePO medicinePO : medicines) {
				HLHandoverRecordMedicine m = new HLHandoverRecordMedicine();

				BeanUtils.copyProperties(medicinePO, m, "id");

				m.setCreatedBy(bindedBabyVO.getId());
				m.setCreated(new Date());
//				m.setHandoverRecord(ret);
				m.setHandoverRecordId(ret.getId());

				batch.add(m);
			}

			medicineRepository.saveAll(batch);
		}

		return ret;
	}

}
